/**
 * 数字添加千分符
 * @param num
 * @returns {string|*}
 */
export const thousandBitSeparator = (num) => {
  if (num) {
    if (num.toString().indexOf('.') !== -1) {
      return num.toString().replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => $1 + ',')
    } else {
      return num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, ($0, $1) => $1 + ',')
    }
  } else {
    return num
  }
}

/**
 * 将日期转为需要的格式
 * @param time  日期
 * @param pattern    日期格式表达式
 * @returns {string}    指定格式的日期
 */
export const dateFormat = (time, pattern = 'yyyy-MM-dd') => {
  const t = new Date(time)
  const tf = (i) => {
    return (i < 10 ? '0' : '') + i
  }
  return pattern.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear())
      case 'MM':
        return tf(t.getMonth() + 1)
      case 'mm':
        return tf(t.getMinutes())
      case 'dd':
        return tf(t.getDate())
      case 'HH':
        return tf(t.getHours())
      case 'ss':
        return tf(t.getSeconds())
    }
  })
}
